#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/3/3 9:11 
# @File           : tools.py
# @IDE            : PyCharm
# @desc           : 工具类

import datetime
import os
from application.settings import TEMP_DIR


def get_week_date(vdate: datetime) -> list:
    """
    获取指定日期所在的周的每一天
    """
    dayscount = datetime.timedelta(days=vdate.isoweekday())
    dayfrom = vdate - dayscount + datetime.timedelta(days=1)
    week7 = []
    i = 0
    while i <= 6:
        week7.append(str(dayfrom + datetime.timedelta(days=i)))
        i += 1
    return week7


def clac_time_diff(start_date: str, end_date: str = None):
    """
    获取时间差
    :param start_date: %Y-%m-%d %H:%M:%S
    :param end_date: %Y-%m-%d %H:%M:%S
    :return: 秒
    """
    start_time = datetime.datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
    if not end_date:
        end_time = datetime.datetime.now()
    else:
        end_time = datetime.datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
    return int((start_time - end_time).total_seconds())


class TimeClac:
    """
    时间计算
    """

    def __init__(self, vtime: str):
        """
        初始化时间
        :param vtime: %Y-%m-%d %H:%M:%S
        """
        self.vtime = vtime
        self.ptime = datetime.datetime.strptime(vtime, "%Y-%m-%d %H:%M:%S")

    def subtraction(self, seconds: int, obj: bool = False):
        """
        减去秒数
        :param seconds: 秒数
        :param obj: 是否返回时间对象
        :return:
        """
        result = self.ptime - datetime.timedelta(seconds=seconds)
        if obj:
            return result
        return result.strftime("%Y-%m-%d %H:%M:%S")


def save_tmp_file(file, data):
    """
    保存临时文件
    """
    date = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d")
    file_dir = os.path.join(TEMP_DIR, date)
    if not os.path.exists(file_dir):
        os.mkdir(file_dir)
    with open(os.path.join(file_dir, file.filename), "wb") as f:
        f.write(data)


if __name__ == '__main__':
    vdate_str = '2022-03-27 13:20:00'
    vdate = clac_time_diff(vdate_str)
    print(vdate)